from fastapi import HTTPException
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse

from config import allow_routes
from utils.auth_util import parse_token_from_request
from utils.jwt_util import verify_token


# JWT 登录认证
class JwtMiddleware(BaseHTTPMiddleware):

    def __init__(self, app):
        super().__init__(app)

    async def dispatch(self, request, call_next):

        # 静态文件路径
        if request.url.path.startswith("/static"):
            return await call_next(request)
        # 放行的api路径
        if request.url.path in allow_routes:
            return await call_next(request)

        try:
            token = parse_token_from_request(request)
            print(f"parsed token = {token}")
            payload = verify_token(token)
            print(f"payload = {payload}")
        except HTTPException as e:
            return JSONResponse(
                status_code=e.status_code,
                content={"message": e.detail}
            )

        return await call_next(request)
